package com.csm.admin.controller;

import com.csm.admin.bean.User1;
import com.csm.admin.bean.User2;
import com.csm.admin.service.User2Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;


/**
 * @author csm
 */
@Slf4j
@Controller
public class IndexController {

    @Autowired
    User2Service user2Service;

    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/getUser2ById")
    public User2 getUser2ById(int id) {
        return user2Service.getUser2ById(id);
    }

    /**
     * 来登录页
     * @return
     */

    @GetMapping(value = {"/", "/login"})
    public String loginPage() {
        return "login";
    }

    @ResponseBody
    @GetMapping("/add")
    public int tadd() {
        int a = 1;
        int b = 2;
        return a+b;
    }

    @PostMapping("/login")
    public String main(User1 user1, HttpSession session, Model model) {
        if (!StringUtils.isEmpty(user1.getUsername()) && "123456".equals(user1.getPassword())) {
            //把登录成功的用户保存起来
            session.setAttribute("loginUser", user1);
            //登录成功重定向到main.html,防止表单重复提交
            return "redirect:/main.html";
        } else {
            model.addAttribute("msg", "账号密码错误");
            //回到登录页面
            return "login";
        }

    }

    /**
     * 去main页面
     * @return
     */
    @GetMapping("/main.html")
    public String mainPage(HttpSession session, Model model) {
//        log.info("当前方法是：{}","mainPage");
//        //是否登录。 拦截器，过滤器
//        Object loginUser = session.getAttribute("loginUser");
//        if (loginUser != null) {
//            return "main";
//        }else {
//            //回到登录页面
//            model.addAttribute("msg", "请重新登录");
//            return "login";
//        }
        ValueOperations<String, String> operations =
                redisTemplate.opsForValue();
        String s = operations.get("/main.html");
        String s1 = operations.get("/add");

        model.addAttribute("mainCount", s);
        model.addAttribute("addCount", s1);
        return "main";
    }
}
